package com.annet.token.dto;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.annet.token.dto.error.ErrorCode;
import lombok.Data;
//import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.io.Serializable;

/**
 * @author yanhu
 * @date 2018/5/21
 */
@Data
public class ResponseDTO implements Serializable {

    public int code = 0;
    public String error = "";
    public Object data;

    @JsonInclude(JsonInclude.Include.NON_NULL)
    private Long runTime;

    public static ResponseDTO onSuccess(Object data) {
        ResponseDTO resp = new ResponseDTO();
        resp.data = data;
        return resp;
    }

    /**
     * 失败DTO
     *
     * @param errorCode
     * @return
     */
    public static ResponseDTO onError(ErrorCode errorCode) {
        ResponseDTO resp = new ResponseDTO();
        resp.code = errorCode.getCode();
        resp.error = errorCode.getMsg();
        return resp;
    }

    public static ResponseDTO onError(ErrorCode errorCode, String error) {
        ResponseDTO resp = new ResponseDTO();
        resp.code = errorCode.getCode();
        if (null != error) {
            resp.error = error;
        } else {
            resp.error = errorCode.getMsg();
        }
        return resp;
    }

    public static ResponseDTO onError(ErrorCode errorCode, Object data) {
        ResponseDTO resp = new ResponseDTO();
        resp.code = errorCode.getCode();
        resp.error = errorCode.getMsg();
        resp.data = data;
        return resp;
    }

    public static ResponseDTO onError(ErrorCode errorCode, String error, Object data) {
        ResponseDTO resp = new ResponseDTO();
        resp.code = errorCode.getCode();
        if (null != error) {
            resp.error = error;
        } else {
            resp.error = errorCode.getMsg();
        }
        resp.data = data;
        return resp;
    }


    /**
     * 失败DTO + 事务回滚
     *
     * @param errorCode
     * @return
     */
/*    public static ResponseDTO onErrorRollback(ErrorCode errorCode) {
        // 事务回滚
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        ResponseDTO resp = new ResponseDTO();
        resp.code = errorCode.getCode();
        resp.error = errorCode.getMsg();
        return resp;
    }*/

    public static ResponseDTO onError(String errorMsg) {
        ResponseDTO resp = new ResponseDTO();
        resp.code = 10;
        resp.error = errorMsg;
        return resp;
    }

    public static ResponseDTO onParamError(String error) {
        ResponseDTO resp = new ResponseDTO();
        resp.code = 11;
        resp.error = error;
        return resp;
    }

    public boolean success() {
        return this.code == 0;
    }

    public boolean error() {
        return !success();
    }

}
